from django.contrib import admin
from django.contrib.admin.sites import NotRegistered
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User, Group
from .forms import UserCreationForm, UserChangeForm


try:
   admin.site.unregister(User)
except NotRegistered:
    pass
    
def get_fieldsets_without_email(fieldsets):
    for fieldset in fieldsets:
        fieldset[1]['fields'] = [field for field in fieldset[1]['fields'] if field != 'email']
    
    return fieldsets
    
    
class EmailUserAdmin(UserAdmin):
    form = UserChangeForm
    add_form = UserCreationForm
    
    list_display = ('username', 'first_name', 'last_name', 'is_staff')
    fieldsets = get_fieldsets_without_email(UserAdmin.fieldsets)
    
    def save_model(self, request, obj, form, change):
        obj.email = obj.username
        obj.save()
admin.site.register(User, EmailUserAdmin)

